package com.rightrule.utils.Impl;

import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.function.Consumer;
import java.util.function.Function;

@Component
public class TransactionHelper {

    // todo 可根据数据库配置文件名进行指定注入
    @Resource
    private TransactionTemplate transactionTemplate;


    /**
     * 无需返回值，直接执行
     *
     * @param action
     */
    public void inTx(Consumer<TransactionStatus> action) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                action.accept(status);
            }
        });
    }


    /**
     * 有返回值
     *
     * @param func
     * @param <T>
     * @return
     */
    public <T> T inTx(Function<TransactionStatus, T> func) {
        return transactionTemplate.execute(new TransactionCallback<T>() {
            @Override
            public T doInTransaction(TransactionStatus status) {
                return func.apply(status);
            }
        });
    }
}
